<template>
    <view class="g_content">
        <view class="dis_f_c_c">
            <u-tabs :list="tabList" :current="currentIndex" lineColor="#27AC2F" @click="handleTab"></u-tabs>
        </view>
        <view v-if="list.length>0">
            <view v-for="(item,index) in list" :key="index">
                <uni-card>
                    <view class="dis_f_r_c">
                        <u-tag v-if="item.state==1" text="待审核" size="mini" plain type="warning"></u-tag>
                        <u-tag v-if="item.state==2" text="审核通过" size="mini" plain type="success"></u-tag>
                        <u-tag v-if="item.state==3" text="审核驳回" size="mini" plain type="error"></u-tag>
                    </view>
                    <u-divider></u-divider>
                    <view>地区：{{item.city}}</view>
                    <view class="dis_f_l">
                        <view>广告：</view>
                        <video :src="item.urlLink" style="width: 50%;height: 200rpx;"></video>
                    </view>
                    <view class="c_red m_t_5" v-if="item.state==3">驳回原因：{{item.remarks}} </view>
                    <u-divider></u-divider>
                    <view class="dis_f_r_c" v-if="item.state!=2">
                        <view>
                            <u-button type="primary" size="mini" @click="handleEdit(item)">编辑</u-button>
                        </view>
                    </view>
                </uni-card>
            </view>
        </view>
        <view class="m_t_100"  v-else>
            <s-empty ></s-empty>
        </view>
        <!-- 授权弹窗 -->
        <s-auth-modal />
        <uni-fab
            :pattern="pattern"
            horizontal="right"
            vertical="bottom"
            direction="horizontal"
            @fabClick="fabClick"
        ></uni-fab>
        <u-modal :show="show" title="发布广告" showCancelButton @cancel="handleCancel" @confirm="handleConfirm">
            <u--form
                labelPosition="top"
                labelWidth="auto"
                :model="queryData"
                ref="uForm"
            >
                <u-form-item
                    label="地区"
                    prop="queryData.cityId"
                    ref="item1"
                >
                    <uni-data-picker v-model="queryData.cityId" :localdata="areaList" placeholder="请选择地区" popup-title="请选择地区" @change="onchange"  ></uni-data-picker>
                </u-form-item>
                <u-form-item
                    label="广告"
                    prop="userInfo.address"
                    ref="item1"
                >
                    <u-upload
                        :fileList="fileList1"
                        @afterRead="afterRead"
                        @delete="deletePic"
                        name="1"
                        multiple
                        :maxCount="1"
                        accept="video"
                    >
                    </u-upload>
                    <view class="c_9 f_s_12">请上传广告的不大于{{adTime}}秒</view>
                </u-form-item>
                <u-form-item
                    v-if="fileList1.length>0"
                    label="已上传广告"
                    ref="item1"
                >
                    <video :src="fileList1[0].url" style="width: 50%;height: 200rpx;"></video>
                </u-form-item>
            </u--form>
        </u-modal>
    </view>
</template>
<script>
import {myMixins} from "@/mixins/myMixins";
import {getAreaListApi, getAdvertisingApi, advertisingApi, getByKeyApi,topUpApi,getCountOfRegionsApi} from "@/sheep/api";
import {baseUrl} from "@/sheep/request/baseUrl";
import { mapGetters, mapMutations } from "vuex";
export default {
    mixins: [myMixins],
    name: "mySend",
    data() {
        return {
            videoUrl:'',
            adTime:0,
            type:'',
            tabList: [{name: '待审核'}, {name: '已通过'}, {name: '已驳回'},],
            currentIndex: 0,
            list: [],
            pattern: {
                color: '#7A7E83',
                backgroundColor: '#fff',
                selectedColor: '#27AC2F',
                buttonColor: '#27AC2F',
                iconColor: '#fff'
            },
            show:false,
            fileList1:[],
            areaList:[],
            queryData:{
                state:1
            },
            payAd:0,
            topUpForm: {
                payWay: "WX_XCX_PAY",
                amount: "",
                attach: "",
                orderType: "advertising",
                desc: "广告发布",
            },
        }
    },
    onShow() {
        this.updateData()
        this.getArea()
        this.getPayAd()
        this.getadTime()
    },
    computed: {
        ...mapGetters(["userInfo"]),
    },
    methods: {

        async getadTime() {
            let res = await getByKeyApi("adTime");
            this.adTime = res.data[0]?.configValue;
        },
        async getPayAd() {
            let res = await getByKeyApi("payAd");
            this.payAd = res.data[0].configValue;
            this.topUpForm.amount = this.payAd;
        },
        getArea(){
            getAreaListApi().then(res=>{
                this.areaList = res.data
            })
        },
        onchange(e) {
            const value = e.detail.value
            if (value.length>0){
                this.queryData.city= value[1].text
                this.topUpForm.attach= value[1].text
                this.queryData.cityId= value[2].value
            }else{
                this.topUpForm.attach= ''
                this.queryData.city = ''
                this.queryData.cityId = ''
            }
        },
        handleToDetail(item) {
            uni.navigateTo({
                url: '/pages/info/index?userId=' + item.userId
            })
        },
        getList() {
            this.queryObj.state = this.currentIndex + 1
            this.queryObj.createBy = this.userInfo.userId
            getAdvertisingApi(this.queryObj).then(res => {
                this.list = this.list.concat(res.rows)
                this.total = res.total
                if (this.queryObj.pageNum * this.queryObj.pageSize < this.total) {
                    this.status = 'loadmore'
                } else {
                    this.status = 'nomore'
                }
                uni.stopPullDownRefresh()
            })
        },
        handleTab(e) {
            this.currentIndex = e.index
            this.updateData()
        },
        fabClick(){
            this.type='add'
            this.show=true
        },
        handleEdit(item){
            this.type='edit'
            this.queryData.advertisingId = item.advertisingId
            this.queryData.cityId = Number(item.cityId)
            this.queryData.city = item.city
            this.fileList1 = [
                {
                    url: item.urlLink,
                    ossId: item.url
                }
            ]
            this.show=true
        },
        handleCancel(){
            this.fileList1 = []
            this.queryData = {
                cityId:'',
                city:'',
            }
            this.show=false
        },
        handleConfirm(){
            if (!this.queryData.city){
                uni.showToast({
                    title: '请选择城市',
                    icon: 'none'
                })
                return
            }
            if (this.fileList1.length==0){
                uni.showToast({
                    title: '请上传广告',
                    icon: 'none'
                })
                return
            }
            if (Array.isArray(this.fileList1)) {
                if (this.fileList1.length > 0) {
                    this.fileList1.forEach((item, index) => {
                        if (index === 0) {
                            this.queryData.url = item.ossId;
                        } else {
                            this.queryData.url = this.queryData.url + "," + item.ossId;
                        }
                    });
                } else {
                    this.queryData.url = "";
                }
            }
            //每个地区只能发200条   编辑不需要支付


            getCountOfRegionsApi({city:this.queryData.city}).then(res=>{
                if (res.code==200){
                    if (this.type=='edit'){
                        this.handleSend()
                    }else{
                        this.handlePay()
                    }

                }
            })
/*
            if (this.userInfo.publishCount>0||this.type=='edit'){
                this.queryData.paymentMeans=1
                this.handleSend()
            }else{
                this.queryData.paymentMeans=2
                this.handlePay()
            }*/

        },
        handleSend(){
            advertisingApi(this.queryData).then(res=>{
                uni.showToast({
                    title: res.msg,
                    icon: 'none'
                })
                if (res.code==200){
                    this.show=false
                    this.handleCancel()
                    this.updateData()
                }
            })
        },
        handlePay(){
            topUpApi(this.topUpForm).then(
                ({ data }) => {
                    let that = this;
                    uni.requestPayment({
                        provider: "wxpay",
                        timeStamp: data.timeStamp,
                        nonceStr: data.nonceStr,
                        package: data.packageValue,
                        signType: data.signType,
                        paySign: data.paySign,
                        success: function(res) {
                            uni.showToast({
                                title: '支付成功',
                                icon: 'none',
                                duration: 2000
                            })
                            that.handleSend()
                            that.updateData()
                        },
                        fail: function(err) {},
                    });
                });
        },
        // 上传图片
        async afterRead(event) {
            let lists = [].concat(event.file);
            console.log("lists", lists);
            let fileListLen = this[`fileList${event.name}`].length;
            lists.map((item, index) => {
                this[`fileList${event.name}`].push({
                    ...item,
                    status: "uploading",
                    message: "上传中",
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url, lists, event);
                console.log("result", result);
                let item = this[`fileList${event.name}`][fileListLen];
                this[`fileList${event.name}`].splice(
                    fileListLen,
                    1,
                    Object.assign(item, {
                        status: "success",
                        message: "",
                        url: result.url,
                        name: result.fileName,
                        ossId: result.ossId
                    })
                );
                fileListLen++;
            }
        },
        uploadFilePromise(url, lists, event) {
            let token = uni.getStorageSync('token')
            let headerToken = "Bearer " + token
            return new Promise((resolve, reject) => {
                let a = uni.uploadFile({
                    url: baseUrl + "/resource/oss/upload",
                    filePath: url,
                    name: "file",
                    header: {
                        Authorization: headerToken,
                        clientId: "be7052a7e4f802c20df10a8d131adb12"
                    },
                    formData: {
                        user: "test",
                    },
                    success: (res) => {
                        let data = JSON.parse(res.data);
                        console.log("data", data);
                        if (data.code == 200) {
                            resolve(data.data);
                        } else {
                            if (lists.length > 0) {
                                lists.map((item, index) => {
                                    this[`fileList${event.name}`].splice(index, 1)
                                });
                            }
                            uni.showToast({
                                title: data.msg,
                                icon: "none",
                            });
                        }
                    },
                });
            });
        },
        // 删除图片
        deletePic(event) {
            this[`fileList${event.name}`].splice(event.index, 1);
        },
    }
}
</script>

<style scoped lang="scss">
/deep/ .u-modal__content{
    display: unset!important;
}
</style>
